﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;


using WebApplication1;

namespace myproject
{
    public partial class luoxuan : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {

            }
            else
            {
                FillData();
            }
        }

        private void FillData()
        {
            var luoxuan = "select * from threethousand";

            var laoer = DbHelper.GetData(luoxuan);
            gv2.DataSource = laoer;
            gv2.DataBind();
        }

        protected void gv2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv2.EditIndex = -1;
            FillData();
        }

        protected void gv2_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = Getvalue(e.RowIndex, 0);

            var sql = string.Format("delete from threethousand where Id = {0}", id);
            DbHelper.SenYe(sql);
            gv2.EditIndex = -1;
            FillData();
        }

        private String Getvalue(int rowIndex,int colIndex)
        {
            var d = gv2.Rows[rowIndex].Cells[colIndex];
            var value = d.Controls.Count > 0 ? ((TextBox)d.Controls[0]).Text : d.Text;
            return value;
        }

        protected void gv2_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv2.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void gv2_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var Add = Getvalue(e.RowIndex, 0);
            var IsOk = int.TryParse(Add, out int id);
            var Name = Getvalue(e.RowIndex, 1);
            var Address = Getvalue(e.RowIndex, 2);
            var Remarks = Getvalue(e.RowIndex, 3);

            if (IsOk)
            {
                var sql = string.Format("update threethousand set Name = '{0}',Address='{1}',Remarks='{2}' where id = '{3}'", Name, Address, Remarks, id);
                DbHelper.SenYe(sql);
            }
            else
            {
                var sql = string.Format("insert into threethousand(Name,Address,Remarks)values('{0}','{1}','{2}')", Name, Address, Remarks);
                DbHelper.SenYe(sql);
            }

            gv2.EditIndex = -1;
            FillData();
        }

        protected void AddMan_Click(object sender, EventArgs e)
        {
            var sql = "select * from threethousand";
            var dn = DbHelper.GetData(sql);
            var su = dn.Copy();
            su.Rows.Add(su.NewRow());

            gv2.DataSource = su;
            gv2.DataBind();

            gv2.EditIndex = su.Rows.Count - 1;
            gv2.DataSource = su;
            gv2.DataBind();

        }
    }
}